<template>
  <div class="meeting-management">
    <div class="search-section">
      <el-input
        v-model="filters.meetingName"
        placeholder="会议名称"
        class="search-input"
      ></el-input>
      <el-input
        v-model="filters.creator"
        placeholder="创建人"
        class="search-input"
      ></el-input>
      <el-date-picker
        v-model="filters.startTime"
        type="date"
        placeholder="开始时间"
      ></el-date-picker>
      <el-button type="primary" @click="searchMeetingsOnInput">搜索</el-button>
      <el-button type="success" @click="exportMeetings">导出</el-button>
      <el-button type="primary" @click="showAddMeetingModal">新增</el-button>
      <el-button type="primary" @click="resetFilters">重置</el-button>
    </div>

    <!-- 会议列表 -->
    <el-table :data="meetings" stripe>
      <el-table-column prop="name" label="会议名称"></el-table-column>
      <el-table-column prop="creator" label="创建人"></el-table-column>
      <el-table-column
        prop="formattedStartTime"
        label="开始时间"
      ></el-table-column>
      <el-table-column prop="status" label="状态"></el-table-column>
      <el-table-column prop="content" label="会议内容"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button
            type="primary"
            size="mini"
            @click="showEditMeetingModal(scope.row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            size="mini"
            @click="confirmDeleteMeeting(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
      class="custom-pagination"
    />
    <!-- 新增/修改会议弹窗 -->
    <el-dialog
      v-model="meetingModalVisible"
      :title="isEditMode ? '修改会议' : '新增会议'"
      width="600px"
    >
      <el-form
        :model="currentMeeting"
        ref="meetingForm"
        label-width="100px"
        class="meeting-form"
        :rules="rules"
      >
        <el-form-item label="会议名称" prop="name">
          <el-input v-model="currentMeeting.name"></el-input>
        </el-form-item>
        <el-form-item label="会议封面" prop="cover">
          <el-upload
            class="avatar-uploader"
            list-type="picture-card"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeCoverUpload"
          >
            <i v-if="!currentMeeting.cover" class="el-icon-plus"></i>
            <img v-else :src="currentMeeting.cover" class="avatar" />
            <div v-if="currentMeeting.cover" class="avatar-mask" @click="triggerUpload">
              <el-button type="text">更换图片</el-button>
            </div>
          </el-upload>
          <div class="el-upload__text">点击或拖动文件到此处，上传</div>
          <div class="el-upload__tip">只能上传 JPG/PNG 格式，且不超过 500kb</div>
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="currentMeeting.creator"></el-input>
        </el-form-item>
        <el-form-item label="会议内容" prop="content">
          <TextEditor v-model="currentMeeting.content" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="currentMeeting.startTime"
            type="datetime"
            placeholder="选择日期和时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="currentMeeting.endTime"
            type="datetime"
            placeholder="选择日期和时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="isEditMode ? updateMeeting() : createMeeting()"
            >{{ isEditMode ? "修改" : "新增" }}</el-button
          >
          <el-button @click="meetingModalVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import TextEditor from './TextEditor.vue';
import { useRouter } from 'vue-router';
axios.defaults.withCredentials = true;

interface Meeting {
  id?: number;
  name: string;
  cover: string;
  creator: string;
  content: string;
  startTime: string;
  endTime: string;  // 添加结束时间
  formattedStartTime?: string;
  status: string;
}

const filters = reactive({
  meetingName: "",
  creator: "",
  startTime: "",
  status: "",
  content: "",
});

interface UserInfo {
  role: string;
  enterprise: string;
  username: string;
}

const meetings = ref<Meeting[]>([]);
const meetingModalVisible = ref(false);
const isEditMode = ref(false);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

const handlePageChange = (page: number) => {
  currentPage.value = page;
  searchMeetings(); // 请求新的分页数据
};

const userInfo = ref<UserInfo | null>(null); 
const userInfoLoaded = ref(false);
const router = useRouter();

function loadUserInfo() {
  const storedRole = localStorage.getItem('role');
  const storedEnterprise = localStorage.getItem('enterprise');
  const storedUsername = localStorage.getItem('username');
  
  if (storedRole && storedEnterprise && storedUsername) {
    userInfo.value = {
      role: storedRole,
      enterprise: storedEnterprise,
      username: storedUsername,
    };
    userInfoLoaded.value = true;
  } else {
    router.push('/login'); // 如果本地存储中没有用户信息，则跳转到登录页面
  }
}

const currentMeeting = reactive<Meeting>({
  name: "",
  cover: "",
  creator: "",
  content: "",
  startTime: "",
  endTime: "",  // 添加结束时间
  status: "",
});

const rules = {
  name: [{ required: true, message: "会议名称不能为空", trigger: "blur" }],
  cover: [{ required: true, message: "请上传会议封面", trigger: "change" }],
  creator: [{ required: true, message: "创建人不能为空", trigger: "blur" }],
  content: [{ required: true, message: "会议内容不能为空", trigger: "blur" }],
  startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  endTime: [{ required: true, message: "请选择结束时间", trigger: "change" }], // 添加结束时间规则
};

const formatDateTime = (dateTime: string) => {
  const options: Intl.DateTimeFormatOptions = {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  };
  return new Date(dateTime).toLocaleString("zh-CN", options);
};

const searchMeetingsOnInput = async () => {
  try {
    if (!userInfo.value) {
      ElMessage.error("用户信息未加载");
      return;
    }
    const params = {
      name: filters.meetingName || undefined,
      creator: filters.creator || undefined,
      startTime: filters.startTime ? new Date(filters.startTime).toISOString() : undefined,
      page: currentPage.value,
      pageSize: pageSize.value,
      enterprise: userInfo.value.enterprise,
    };

    const url = userInfo.value.role === "超级管理员"
      ? "http://localhost:1111/meeting/search"
      : "http://localhost:1111/meeting/search/tenant";

    const response = await axios.get(url, { params });

    if (response.data.isOK) {
      meetings.value = response.data.data.map((meeting: Meeting) => {
        if (new Date(meeting.startTime).getFullYear() < 1980) {
          return { ...meeting, formattedStartTime: null };
        } else {
          return { ...meeting, formattedStartTime: formatDateTime(meeting.startTime) };
        }
      });
      total.value = response.data.total; // 设置总数
      ElMessage.success("搜索成功");
    } else {
      ElMessage.error(response.data.msg || "搜索失败");
    }
  } catch (error) {
    console.error("搜索会议时出错！", error);
    ElMessage.error("搜索失败");
  }
};

const searchMeetings = async () => {
  try {
    if (!userInfo.value) {
      ElMessage.error("用户信息未加载");
      return;
    }
    const params = {
      ...filters,
      page: currentPage.value,
      pageSize: pageSize.value,
      enterprise: userInfo.value.enterprise,
    };

    const url = userInfo.value.role === "超级管理员"
      ? "http://localhost:1111/meeting/admin/list"
      : "http://localhost:1111/meeting/list";

    const response = await axios.get(url, { params });

    meetings.value = response.data.data.map((meeting: Meeting) => {
      if (new Date(meeting.startTime).getFullYear() < 1980) {
        return { ...meeting, formattedStartTime: null };
      } else {
        return { ...meeting, formattedStartTime: formatDateTime(meeting.startTime) };
      }
    });

    total.value = response.data.total; // 设置总数
  } catch (error) {
    ElMessage.error("获取会议列表失败");
  }
};

const resetFilters = () => {
  filters.meetingName = "";
  filters.creator = "";
  filters.startTime = "";
  filters.status = "";
  filters.content = "";
  searchMeetings(); // Optionally, you can call searchMeetings here to refresh the list
};

const exportMeetings = async () => {
  try {
    const params = {
      name: filters.meetingName || undefined,
      creator: filters.creator || undefined,
      startTime: filters.startTime ? new Date(filters.startTime).toISOString() : undefined,
    };
    const response = await axios.get('http://localhost:1111/api/meetings/export', {
      params,
      responseType: 'blob',
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'meetings.xlsx');
    document.body.appendChild(link);
    link.click();
  } catch (error) {
    ElMessage.error('导出会议列表失败');
  }
};

const showAddMeetingModal = () => {
  resetCurrentMeeting();
  isEditMode.value = false;
  meetingModalVisible.value = true;
};

const showEditMeetingModal = (meeting: Meeting) => {
  Object.assign(currentMeeting, meeting);
  isEditMode.value = true;
  meetingModalVisible.value = true;
};

const handleCoverSuccess = (response: any) => {
  currentMeeting.cover = response.url;
};

const beforeCoverUpload = async (file: File) => {
  const isImage = file.type === "image/jpeg" || file.type === "image/png";
  if (!isImage) {
    ElMessage.error("图片格式不正确");
    return false; // 阻止默认的上传行为
  }

  const isLt500K = file.size / 1024 / 1024 < 2;
  if (!isLt500K) {
    ElMessage.error("图片大小不能超过 2mb");
    return false; // 阻止默认的上传行为
  }

  try {
    const formData = new FormData();
    formData.append("file", file);

    const response = await axios.post(
      "http://localhost:1111/api/upload",
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }
    );

    handleCoverSuccess(response.data);
    return false; // 阻止默认的上传行为
  } catch (error) {
    ElMessage.error("图片上传失败");
    return false; // 阻止默认的上传行为
  }
};

const triggerUpload = () => {
  const upload = document.querySelector('.avatar-uploader input[type=file]') as HTMLElement;
  if (upload) {
    upload.click();
  }
};

const createMeeting = async () => {
  try {
    if (!userInfo.value) {
      ElMessage.error("用户信息未加载");
      return;
    }

    // 将 currentMeeting 对象直接传递给后端
    await axios.post("http://localhost:1111/meeting/add", {
      ...currentMeeting,
      endTime: currentMeeting.endTime, // 确保 endTime 不为 undefined
      enterprise: userInfo.value.enterprise,
    });
    ElMessage.success("会议创建成功");
    meetingModalVisible.value = false;
    searchMeetings(); // 刷新会议列表
  } catch (error) {
    ElMessage.error("会议创建失败");
  }
};

const updateMeeting = async () => {
  try {
    await axios.post("http://localhost:1111/meeting/update", {
      ...currentMeeting,
      endTime: currentMeeting.endTime, // 确保 endTime 不为 undefined
    });
    ElMessage.success("会议修改成功");
    meetingModalVisible.value = false;
    searchMeetings();
  } catch (error) {
    ElMessage.error("会议修改失败");
  }
};

const confirmDeleteMeeting = (meeting: Meeting) => {
  ElMessageBox.confirm("是否删除该会议?", "提示", {
    confirmButtonText: "是",
    cancelButtonText: "否",
    type: "warning",
  })
    .then(() => {
      deleteMeeting(meeting);
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const deleteMeeting = async (meeting: Meeting) => {
  try {
    await axios.delete('http://localhost:1111/meeting/delete', {
      params: { id: meeting.id },
    });
    ElMessage.success("会议删除成功");
    searchMeetings(); // 刷新会议列表
  } catch (error) {
    ElMessage.error("会议删除失败");
  }
};

const resetCurrentMeeting = () => {
  currentMeeting.name = "";
  currentMeeting.cover = "";
  currentMeeting.creator = "";
  currentMeeting.content = "";
  currentMeeting.startTime = "";
  currentMeeting.status = "";
};

onMounted(() => {
  loadUserInfo();
  searchMeetings();
});
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader .el-upload .el-icon-plus {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  line-height: 100px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
  border-radius: 0;
}

.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 14px;
  cursor: pointer;
}

.meeting-management {
  padding: 20px;
}

.search-section {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  width: 200px;
}

.meeting-form {
  max-width: 600px;
  margin: 0 auto;
}

.el-table .el-table__header-wrapper {
  background-color: #f5f7fa;
}

.el-table .el-table__body-wrapper {
  background-color: #fff;
}

.el-table .el-table__row {
  transition: background-color 0.3s;
}

.el-table .el-table__row:hover {
  background-color: #f0f9ff;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
}

.el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
  color: #fff;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}

.el-dialog__header {
  background-color: #f5f7fa;
}

.el-dialog__body {
  background-color: #fff;
}

.custom-pagination {
  /* 覆盖或自定义分页组件的样式 */
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.custom-pagination .el-pager li {
  background-color: #f0f0f0; /* 自定义背景颜色 */
  border-radius: 5px; /* 圆角 */
  margin: 0 5px; /* 间距 */
  padding: 8px 16px; /* 内边距 */
  cursor: pointer; /* 鼠标悬停效果 */
  transition: background-color 0.3s; /* 平滑过渡效果 */
}

.custom-pagination .el-pager li:hover {
  background-color: #e0e0e0; /* 悬停背景颜色 */
}

.custom-pagination .el-pager li.active {
  background-color: #409EFF; /* 当前页的背景颜色 */
  color: #fff; /* 当前页的文字颜色 */
  font-weight: bold; /* 当前页的文字加粗 */
}

.custom-pagination .el-pagination__prev,
.custom-pagination .el-pagination__next {
  color: #409EFF; /* 前一页和后一页按钮的颜色 */
  margin: 0 10px; /* 间距 */
}

.custom-pagination .el-pagination__prev:hover,
.custom-pagination .el-pagination__next:hover {
  color: #307bbf; /* 按钮悬停颜色 */
}

.custom-pagination .el-pagination__jump {
  display: flex;
  align-items: center;
}

.custom-pagination .el-pagination__jump .el-input__inner {
  width: 50px; /* 输入框宽度 */
  height: 32px; /* 输入框高度 */
  text-align: center; /* 文本居中 */
  margin: 0 10px; /* 间距 */
}

.custom-pagination .el-pagination__total {
  font-size: 14px; /* 总条目数字体大小 */
  margin: 0 10px; /* 间距 */
}
</style>
